// 提交答案API
import { NextRequest } from 'next/server';
import { AnswerDB, ProgressDB, MistakeDB, AchievementDB } from '@/lib/mysql';
import { getCurrentUser, getTokenFromHeader, ApiResponse } from '@/lib/auth';

// 提交单个题目的答案
export async function POST(request: NextRequest) {
  try {
    // 验证用户登录 - 从Authorization header获取token
    const authHeader = request.headers.get('Authorization');
    const token = getTokenFromHeader(authHeader || '');
    const currentUser = getCurrentUser(token || undefined);
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 解析请求体
    const body = await request.json();
    const {
      sessionId,
      topicId,
      topicName,
      questionIndex,
      questionStem,
      userAnswer,
      correctAnswer,
      isCorrect,
      timeSpent,
      hintsUsed,
      difficulty,
      solution,
    } = body;

    // 验证必填字段
    if (
      !sessionId ||
      !topicId ||
      !topicName ||
      questionIndex === undefined ||
      !questionStem ||
      !correctAnswer ||
      typeof isCorrect !== 'boolean'
    ) {
      console.error('缺少必填字段:', {
        sessionId,
        topicId,
        topicName,
        questionIndex,
        questionStem: questionStem ? '有' : '无',
        correctAnswer: correctAnswer ? '有' : '无',
        isCorrect
      });
      return ApiResponse.error('缺少必填字段');
    }

    // 记录答题
    await AnswerDB.create(
      sessionId,
      currentUser.userId,
      topicId,
      questionIndex,
      questionStem,
      userAnswer || '',
      JSON.stringify(correctAnswer),
      isCorrect,
      timeSpent || 0,
      hintsUsed || 0,
      difficulty || 1
    );

    // 更新学习进度
    await ProgressDB.updateProgress(
      currentUser.userId,
      topicId,
      topicName,
      isCorrect,
      timeSpent || 0
    );

    // 如果答错，添加到错题本
    if (!isCorrect) {
      await MistakeDB.add(
        currentUser.userId,
        topicId,
        topicName,
        questionIndex,
        questionStem,
        JSON.stringify(correctAnswer),
        userAnswer || '',
        solution || '',
        difficulty || 1
      );
    }

    // 检查并解锁成就（异步，不阻塞响应）
    AchievementDB.checkAndUnlock(currentUser.userId).catch(err => 
      console.error('检查成就错误:', err)
    );

    return ApiResponse.success(
      {
        isCorrect,
        recorded: true,
      },
      '答案提交成功'
    );
  } catch (error) {
    console.error('提交答案错误:', error);
    return ApiResponse.serverError('提交答案失败');
  }
}
